﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using Core;
using Core.LockStep;

public class BattleSystem : GameEntitySystem, IAwake
{
    public IBattleDataHelper dataHelper;
    public IBattleAssetHelper assetHelper;

    private BattleInfo battleInfo;

    private IDataEnumerable<BackupData1PlayerData> playerDatas;

    public void Awake()
    {
        dataHelper = GetHelper<IBattleDataHelper>();
        assetHelper = GetHelper<IBattleAssetHelper>();

        playerDatas = LockStepTool.GetBackupDatas<BackupData1PlayerData>();

        Subscribe<OnLockStepBegin>(OnLockStepBegin);
        Subscribe<GetBattleInfo>(GetBattleInfo);
    }

    private void GetBattleInfo(ref GetBattleInfo data)
    {
        if (battleInfo == null)
            return;

        data.battleInfo = battleInfo;

        battleInfo.playerInfos.Clear();
        foreach (var item in playerDatas)
            battleInfo.playerInfos[item.playerId] = item.position.Current;

        var result = new GetLockStepRunningInfo().Publish();
        battleInfo.netDelayTime = result.netDelayTime;
        battleInfo.clientFrameIndex = result.clientFrameIndex;
        battleInfo.serverFrameIndex = result.serverFrameIndex;
    }

    private void OnLockStepBegin(ref OnLockStepBegin data)
    {
        assetHelper.Clear();

        dataHelper.battleInfo = (BattleInfoData)new GetBattleInfoData().Publish().lockstepInfoData;

        // 生成其他玩家
        foreach (var playerId in dataHelper.battleInfo.playerIds)
        {
            assetHelper.CreatePlayer(playerId);
        }

        battleInfo = new BattleInfo();
    }
}